<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>海云数据员工花名册</title>
		<link rel="stylesheet" href="http://show.funlee.cn/api/bootstrap_v3/css/bootstrap.css" />
	</head>
	<body>
		<div id="tools" class="container">
			<div id="adddiv" class="col-lg-4">
				<form>
					<h3>添加员工</h3>
					<label for="name">姓名</label>
					<input type="text" id="name" class="form-control"/><br />
					<label for="date">生日</label>
					<input type="date" id="date" class="form-control"/><br />
					<label for="job">职位</label>
					<input type="text" name="job" id="job" class="form-control"/><br />
					<input type="button" name="add" value="添加" id="add" class="btn btn-primary"/>
					<input type="reset" value="重置表单" class="btn btn-primary"/>
				</form>
			</div>
			<div id="seacherdiv" class="col-lg-4">
				<h3>搜索员工</h3>
				<input type="text" id="seartxt" placeholder="检索姓名"/>
				<input type="button" id="seacher" value="搜索" class="btn btn-primary"/>
			</div>
			<div id="deletediv" class="col-lg-4">
				<h3>删除数据库</h3>
				<input type="button" id="deleteDatabase" value="删除数据库" class="btn btn-primary"/>
				<h3>关闭数据库</h3>
				<input type="button" id="closeDatabase" value="关闭数据库" class="btn btn-primary"/>
			</div>
		</div>
		<div class="container">
			<table id="result" class="table table-striped table-bordered table-hover">
				<caption>
					<h3 class="text-center">海云数据员工花名册</h3></caption>
				<tr>
					<th>编号</th>
					<th>姓名</th>
					<th>生日</th>
					<th>职位</th>
					<th>删除</th>
				</tr>
			</table>
		</div>
		<script type="text/javascript">
			//统一定义
			window.indexedDB = window.indexedDB || window.webketIndexedDB || window.mozIndexedDB || window.msIndexedDB; //indexedDB数据库
			window.IDBTansaction = window.IDBTansaction || window.webkitIDBTansaction || window.msIDBTansaction; //数据库使用的事务
			window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; //IDBkeyRange对象
			window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;  //游标对象
			//初始化数据
			var db;
			var arraykey = [];
			var openRequest;
			var lastCursor;
			var dbName = "staff";
			var dbVersion = 1.0;
			var tablename = "staff";
			//页面加载完成之后执行数据库打开或者初始化
			window.onload = function init() {
					openRequest = indexedDB.open(dbName,dbVersion); //如果数据库存在就打开，如果数据库不存在就去新建
					//1、创建新数据库，或者数据库版本号被更改的时候触发onupgradeneeded事件，并执行回调函数
					openRequest.onupgradeneeded = function(e) {
					 	var thisDb = e.target.result;
						//判断是否有这个表格的存在
						if(!thisDb.objectStoreNames.contains(tablename)) {
							//如果表格不存在，创建一个新的表格（keyPath，主键 ； autoIncrement,是否自增），会返回一个对象（objectStore）
							var objectStore = thisDb.createObjectStore(tablename, {
								keyPath: "id",
								autoIncrement: true
							});
							//指定可以被索引的字段，unique字段是否唯一
							objectStore.createIndex("name", "name", {
								unique: false, //true 代表同一个对象仓库总两条数据记录的索引属性值不能相同
								multiEntry:false
							});
							objectStore.createIndex("job", "job", {
								unique: false,
								multiEntry:false
							});
						}
					}
					//2、打开数据库成功是触发的事件，onsuccess;
					openRequest.onsuccess = function(e) {
						db = e.target.result;
						db.onerror = function(event) {
							alert("数据库错误：" + event.taeget.errorCode);
							console.dir(event.target);
						};
						//判断表格是否存在，存在则遍历数据
						if(db.objectStoreNames.contains(tablename)) {
							//通过事务去操控表格
							var transaction = db.transaction([tablename], "readwrite");
							//事务的回调函数处理
							transaction.oncomplete = function(event) {
								console.log("transaction complete!");
							};
							transaction.onerror = function(event) {
								console.dir(event);
							};
							//得到表里面的objectStore对象
							var objectStore = transaction.objectStore(tablename);
							//使用游标遍历
							objectStore.openCursor().onsuccess = function(event) {
								var cursor = event.target.result;
								if(cursor) {
									render({
										key: cursor.key,
										name: cursor.value["name"],
										date: cursor.value["date"],
										job: cursor.value["job"]
									})
									lastCursor = cursor.key;
									cursor.continue();
								} else {
									console.log("Done with cursor");
								}
							};
							objectStore.openCursor().onerror = function(event) {
								console.dir(event);
							}
						}
					}
					openRequest.onerror = function() {
						console.log("数据库连接失败");
					}

					//添加方法
					document.querySelector("#add").addEventListener("click", function() {
						//初始化一个学生对象
						var name = document.querySelector("#name").value;
						var date = document.querySelector("#date").value;
						var job = document.querySelector("#job").value;
						var staffItem = {
							"name": name,
							"date": date,
							"job": job
						};
						//获取一个事务
						var transaction = db.transaction([tablename], "readwrite");
						//通过事务得到一个objectStore对象
						var objectStore = transaction.objectStore(tablename);
						objectStore.add(staffItem);
						//将新添加的数据，加入到html里面展示
						objectStore.openCursor().onsuccess = function() {
							cursor = event.target.result;
							var key;
							if(lastCursor == null) {
								key = cursor.key;
								lastCursor = key;
							} else {
								key = ++lastCursor;
							}
							render({
								key: key,
								name: name,
								date: date,
								job: job
							});
						}
					},false);
					//查询数据库
					document.querySelector("#seacher").addEventListener("click", function() {
						var curName = document.querySelector("#seartxt").value;
						var transaction = db.transaction([tablename], "readwrite");
						//得到objectStore对象
						var objectStore = transaction.objectStore(tablename);
						var boundKeyRange = IDBKeyRange.only(curName); //生成一个遍历范围的Range对象
						objectStore.index("name").openCursor(boundKeyRange).onsuccess = function(event) {
							var cursor = event.target.result;
							if(!cursor) {
								return;
							}
							var rowData = cursor.value;
							//先清空展示列表
							document.querySelector("#result").innerHTML = "<caption><h3>学生花名册</h3></caption><tr><th>学号</th><th>姓名</th><th>生日</th><th>地址</th><th>删除</th></tr>"
							render({
								key: cursor.key,
								name: cursor.value["name"],
								date: cursor.value["date"],
								job: cursor.value["job"]
							});
							cursor.continue();
						}
					},false)
					//删除数据库
					document.querySelector("#deleteDatabase").addEventListener("click", function() {
						if(confirm("您确定要删除数据库吗？\n操作不可逆")) {
							var dbname = prompt("请输入数据库名称，以确认删除", "");
							if(dbname == dbName) {
								var deleteDB = indexedDB.deleteDatabase(dbName);
								var result = document.querySelector("#result");
								while(result.firstChild.nextSibling) {
									result.removeChild(result.firstChild.nextSibling);
								}
								window.location.reload(true);
							}
						}
					},false);
					//关闭数据库
					document.querySelector("#closeDatabase").addEventListener("click", function() {
						openRequest.result.close();
						console.log("数据库已经关闭");
					},false);
				}
			//删除方法
			function deleteStaff(key) {
				var transaction = db.transaction([tablename], "readwrite");
				transaction.oncomplete = function(event) {
					console.log("transaction complete!");
				};
				transaction.onerror = function(event) {
					console.dir(event);
				}
				//得到objectStore对象
				var objectStore = transaction.objectStore(tablename);
				//接收传过来的key值
				var removeKey = parseInt(key);
				//通过key值获取对象,在控制台打印
				var getRequest = objectStore.get(removeKey);
				getRequest.onsuccess = function(e) {
					var result = getRequest.result;
					console.dir(result);
				};
				var request = objectStore.delete(removeKey);
				request.onsuccess = function(e) {
					console.log("成功删除记录");
				};
				request.onerror = function(e) {
					console.log("Error delete record:", e);
				}
				document.getElementById(removeKey).style.display = "none";

			}
			//将从游标得到的database数据添加到html的方法
			function render(staff) {
				//接收传输的值
				var staff = staff;
				//将结束到的josn数据变成一行表格
				var html = "<tr id='" + staff.key + "'><td>" + staff.key + "</td><td>" + staff.name + "</td><td>" + staff.date + "</td><td>" + staff.job + "</td><td><input type='button' onClick='deleteStaff(" + staff.key + ")' value='删除' />";
				//将得到的表格数据，追加到结果表中去
				
				document.querySelector("#result").innerHTML += html;
			}
		</script>
		
	</body>

</html>